
const recorderManager = wx.getRecorderManager();
const innerAudioContext = wx.createInnerAudioContext();
var init;

const app = getApp();

Page({

  data: {
    Sender:'',
    Time:'',
    recipient:'',
    textContent:'',
    activeIndex: 0 ,
    id : "",
    moreVisible:false,
    previewWord:true,
    allVisible:false,
    previewAll: false, 
    imageList: [],
    videoList: [],
    time: 0,
    duration: 600000,
    tempFilePath: "",
    status: 0,
    playStatus: 0,
    showRecordingLayout: false,  
    showRecordingBar: false,
    isPlaying: false,   
    codeId: '',
    uploadedCount : 0  ,  
    totalCount : 0
  },
  onInputName(e) {
    this.setData({
      Sender: e.detail.value
    });
  },
  switchTab: function(e) {
    const index = parseInt(e.currentTarget.dataset.index); // 获取点击的导航项的索引
    this.setData({
      activeIndex: index // 更新 activeIndex，切换页面内容
    });
  },
  preview:function(){
    this.setData({
      moreVisible:true
    })
  },
  back:function(){
    this.setData({
      moreVisible:false
    })
  },

  previewAll:function(){
    
    let _this = this;
    wx.navigateTo({
      url: '/pages/show/show',
      success: function(res) {
        // 通过 res.eventChannel 传递数据
        res.eventChannel.emit('acceptDataFromOpenerPage', { 
          imageList: _this.data.imageList,
          videoList: _this.data.videoList,
          audioPath: _this.data.tempFilePath,
          textContent: _this.data.textContent,
          recipient: _this.data.recipient,
          Sender: _this.data.Sender,
          Time: _this.data.Time
        });
      },
      fail: function(error)
      {
        console.log(error)
      }
    });
  },
 
  onLoad(options) {
    const _this = this;
    const now = new Date();
    const Time = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')} `;
    this.setData({
      Time: Time
    });
    this.setData({
      code:''
    })
    const eventChannel = this.getOpenerEventChannel();
    if(eventChannel)
    {
      eventChannel.on('acceptDataFromOpenerPage', (data) => {
        this.data.codeId = data.code
  
        console.log(this.data.codeId)
      });
    }
  

    this.onDataLoad();
  },

  onDataLoad:function()
  {

    let _this = this;
    wx.request({
      url: app.serverUrl+'drafts/send',
      method:'GET',
      header:{
        "openid":wx.getStorageSync('openId')
      },
      success(res){

        if(res.data.code === 200)
        {
          const data = res.data.data;
          console.log(data)
          _this.setData({
            id:data.id,
            recipient:data.toName,
            Sender: data.userName,
            textContent:data.content,
            Time:data.date
          })

          _this.downloadResource(data.picturePaths)
          .then((paths)=>{
            console.log(paths)
            _this.setData({
              imageList : paths
            })
          })

          _this.downloadResource(data.videoPaths)
          .then((paths)=>{
            _this.setData({
              videoList : paths
            })
          })
        }
        
       
      },
      fail(err)
      {
        console.log(err)
      }
    })
  },

  downloadResource:function(urls)
  {
    const cachedResourcePaths = [];
    let _this = this;
    return Promise.all(urls.map(url => _this.downloadFile(url)));
  },

  downloadFile:function(url) {
    return new Promise((resolve, reject) => {
      wx.downloadFile({
        url,
        success: res => {
          if (res.statusCode === 200) {
            resolve(res.tempFilePath);
          } else {
            reject(new Error(`Download failed for ${url}`));
          }
        },
        fail: err => {
          reject(err);
        }
      });
    });
  },
 

  onInputRecipient:function(e)
  {
    console.log(e.detail.value)
    this.setData({
      recipient:e.detail.value
    })
  },
  onInputContent:function(e)
  {
    console.log(e.detail.value)
    this.setData({
      textContent:e.detail.value
    })
  },
  onInputSender:function(e)
  {
    console.log(e.detail.value)
    this.setData({
      Sender:e.detail.value
    })
  },
  onInputTime:function(e)
  {
    this.setData({
      Time:e.detail.value
    })
  },


  
  getPhoto:function()
  {
    let _this = this;
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album'],
      success: (res) => {
        var tempFilePaths = res.tempFilePaths;
        const imageNew = _this.data.imageList.concat(tempFilePaths)
        this.setData({
          imageList: imageNew,
          allVisible: true  
          });

        //将图片发送到后端
        // tempFilePaths.forEach(filePath => {
        //  // _this.uploadFile(filePath, '照片');
        // });
      }
    });

  },

  getVideo:function()
  {
    let _this = this;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      success: (res) =>{
        const tempFilePath = res.tempFilePath
        // 根据视频文件进行相关操作
        //将视频传到后端
        console.log(tempFilePath)
        const videoNew = _this.data.videoList.concat(tempFilePath)
        this.setData({
          videoList: videoNew,
          allVisible: true  
          });

          //_this.uploadFile(tempFilePath, '视频');
      }
    })
  },

  uploadFile: function(filePath, fileType) {
    const _this = this;
    const url = app.serverUrl + `receive${fileType.charAt(0).toUpperCase() + fileType.slice(1)}s`; 

    const uploadTask = wx.uploadFile({
      url: url,
      filePath: filePath,
      name: fileType,
      header: {
        'openid': wx.getStorageSync('openId'),
        'qrcode': _this.codeId
      },
      success: function(res) {
        console.log(`${fileType} 上传成功:`, res.data);
        wx.showToast({
          title: `${fileType} 保存成功`,
          icon: 'success',
          duration: 2000
        });
      },
      fail: function(error) {
        console.error(`上传失败:`, error);
        wx.showToast({
          title: `${fileType} 保存失败`,
          icon: 'error',
          duration: 2000
        });
      }
    });

    uploadTask.onProgressUpdate((res) => {
      _this.setData({
        uploadProgress: res.progress
      });

      if (res.progress < 100) {
        wx.showToast({
          title: `正在保存 ${fileType}`,
          icon: 'loading',
          duration: 2000
        });
      } else {
        wx.showToast({
          title: `${fileType} 保存成功`,
          icon: 'success',
          duration: 2000
        });
      }
    });
  },

  groupImages(imagePaths) {
    const imageList1 = []
    for (let i = 0; i < imagePaths.length; i += 3) {
      imageList1.push(imagePaths.slice(i, i + 3))
    }
    return imageList1
  },
  deleteImage(event) {
    const index = event.currentTarget.dataset.index;
    const newImageList = [...this.data.imageList];
    newImageList.splice(index, 1);
    this.setData({
      imageList: newImageList
    });
  },

  deleteVideo(event) {
    const index = event.currentTarget.dataset.index;
    const newImageList = [...this.data.videoList];
    newImageList.splice(index, 1);
    this.setData({
      videoList: newImageList
    });
  },

  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  save:function()
  {
    console.log(this.data.codeId)
    if(this.data.codeId === 'undefined'||this.data.codeId==='' || this.data.codeId === null)
    {
      wx.showToast({
        title: '请先扫描二维码，保存后无法修改',
        icon: 'none'
      })
    }else{
      this.data.totalCount = this.data.imageList.length+this.data.videoList.length;
      const url = app.serverUrl+'qrcode/'
      this.updateContent(url);
      this.updateImages(url)
      this.updateVideo(url)
      this.updateVoice(url)
      this.data.codeId = '';
    }
    
  },
  updateContent:function(url)
  {
    const _this = this;
    wx.request({
      url: url+'save',
      method:'POST',
      data: {
        toName:this.data.recipient,
        userName: this.data.Sender,
        content:this.data.textContent,
        date:this.data.Time
      },
      header:{
        'qrcode': _this.data.codeId
      },
      success(res){
        console.log(res.data.data.id)
        _this.setData({
          id:res.data.data.id
        })
        //_this.uploadedCount++;
        console.log("数据上传成功")
      },
      fail(error)
      {
        //_this.uploadedCount++;
        console.log("上传失败:",error)
      }

    })
  },
  drafts:function()
  {
    this.data.totalCount = this.data.imageList.length+this.data.videoList.length;
    const url = app.serverUrl+'drafts/'
    this.substance(url);
    this.updateImages(url)
    this.updateVideo(url)
    this.updateVoice(url)
  },

  updateUploadProgress() { 
    if (this.data.uploadedCount === this.data.totalCount) {
      // 全部上传完成
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000
      });
    }
    else{
      wx.showToast({
        title: '正在保存,请稍后',
        icon: 'loading',
        duration: 10000
      });
    }
  },

  substance:function(url)
  {
    const _this = this;
    wx.request({
      url: url+'save',
      method:'POST',
      data: {
        id: this.data.id,
        toName:this.data.recipient,
        userName: this.data.Sender,
        content:this.data.textContent,
        date:this.data.Time
      },
      header:{
        'openid':wx.getStorageSync('openId'),
        'qrcode': _this.data.codeId
      },
      success(res){
        console.log(res.data.data.id)
        _this.setData({
          id:res.data.data.id
        })
        //_this.uploadedCount++;
        console.log("数据上传成功")
      },
      fail(error)
      {
        //_this.uploadedCount++;
        console.log("上传失败:",error)
      }

    })
  },
  
  updateImages:function(url)
  {
    const _this = this;
    if(this.data.imageList.length != 0)
    {

      this.data.imageList.forEach(function (filePath) {
        wx.uploadFile({
        url: url+'receiveImages',
          filePath: filePath,
          name: 'images',
          header: {
            'openid':wx.getStorageSync('openId'),
            'qrcode':_this.data.codeId
          },
          success: function (res) {
            _this.data.uploadedCount++;
            console.log("图片上传成功...")
            _this.updateUploadProgress();
          },
          fail(error)
          {
            _this.data.uploadedCount++;
            _this.updateUploadProgress();
            console.log("上传失败:",error)
          }
        })
      })
    }
  },

  updateVideo:function(url)
  {
     const _this = this
    if(this.data.videoList.length != 0)
    {
      this.data.videoList.forEach(function (filePath) {
        wx.uploadFile({
          url: url+'receiveVideos',
          filePath: filePath,
          name: 'videos',
          header: {
            'openid':wx.getStorageSync('openId'),
            'qrcode':_this.data.codeId
            },
          success(uploadRes) {
            _this.data.uploadedCount++;
            _this.updateUploadProgress();
            console.log(uploadRes.data);
          },
          fail(error) {
            _this.data.uploadedCount++;
            _this.updateUploadProgress();
            console.error('上传失败:', error);
          }
        })
      })
    }
  },

  updateVoice:function(url)
  {
    let _this = this;

    const path = this.data.tempFilePath

    if( !(path=== '' || path == 'undefined'||path == null))
    {
      wx.uploadFile({
        filePath: _this.data.tempFilePath,
        name: 'voice',
        url: url+'receiveVoice',
        header: {
          'openid':wx.getStorageSync('openId'),
          'qrcode':_this.codeId
          },
        success(uploadRes) {
          console.log(uploadRes.data);
        },
        fail(error) {
          console.error('上传失败:', error);
        }
      })
    }
  },
  
  togglePlayRecording: function() {
    innerAudioContext.src = this.data.tempFilePath;
    innerAudioContext.obeyMuteSwitch = false;
    if (this.data.isPlaying) {
      innerAudioContext.stop();
      this.setData({ isPlaying: false });
    } else {
      innerAudioContext.play();
      this.setData({ isPlaying: true });
    }
    innerAudioContext.onEnded(() => {
      innerAudioContext.stop();
      this.setData({ isPlaying: false });
    });
  },

  startRecord: function() {
    clearInterval(init);
    recorderManager.onStart((res) => {
      console.log('recorder start');
      this.setData({
        status: 1,
        showRecordingBar: false
      });
    });

    recorderManager.onStop((res) => {
      console.log('recorder stop', res);
      this.setData({
        tempFilePath: res.tempFilePath,
        status: 3,
        showRecordingBar: true  
      });
      this.recordingTimer(this.data.time);
    });

    const options = {
      duration: this.data.duration,
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 96000,
      format: 'mp3',
      frameSize: 50,
    };
    this.recordingTimer();
    recorderManager.start(options);
  },

  stopRecord: function() {
    recorderManager.onStop((res) => {
      console.log('recorder stop', res);
      this.setData({
        tempFilePath: res.tempFilePath,
        status: 3,
        showRecordingBar: true  
      });
    });
    this.recordingTimer(this.data.time);
    recorderManager.stop();
  },

  playRecord: function() {
    innerAudioContext.src = this.data.tempFilePath;
    innerAudioContext.obeyMuteSwitch = false;

    if (this.data.playStatus == 0) {
      this.setData({
        playStatus: 1
      });
      innerAudioContext.play();
    }

    innerAudioContext.onEnded(() => {
      innerAudioContext.stop();
      this.setData({
        playStatus: 0
      });
    });
  },

  recordingTimer: function(time) {
    var that = this;
    if (time == undefined) {
      init = setInterval(function() {
        var time = that.data.time + 1;
        that.setData({
          time: time
        });
      }, 1000);
    } else {
      clearInterval(init);
      console.log("暂停计时");
    }
  },

  resetRecord: function() {
    var that = this;
    wx.showModal({
      title: "重新录音",
      content: "是否重新录制?",
      success(res) {
        if (res.confirm) {
          that.setData({
            time: 0,
            tempFilePath: "",
            status: 0,
            playStatus: 0,
            showRecordingBar: false  
          });
          innerAudioContext.stop();
        }
      }
    });
  },

  toggleRecordingLayout: function() {
    this.setData({
      showRecordingLayout: !this.data.showRecordingLayout
    });
  },

  hideRecordingLayout: function() {
    this.setData({
      showRecordingLayout: false
    });
  }
})